package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domian.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //新增
    @PostMapping
    public R<String> creact(@RequestBody Category creator) {
        categoryService.save(creator);
        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page<Category>> page(Integer page, Integer pageSize) {
        //分页查询集合
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //查询条件对象
//        Long size=10L;
        LambdaQueryWrapper<Category> lambdaQueryWrap = new LambdaQueryWrapper<>();
//        lambdaQueryWrap.eq(Dish::getName,"id");
        lambdaQueryWrap.orderByAsc(Category::getSort);
        lambdaQueryWrap.orderByDesc(Category::getUpdateTime);
        //调用分页查询方法
        categoryService.page(pageInfo, lambdaQueryWrap);
        //返回R封装的分页查询集合
        return R.success(pageInfo);
    }

    //按id删除
    @DeleteMapping
    public R<String> deleteById(Long id) {
        categoryService.remove(id);
        return R.success("删除成功");
    }


    //修改
    @PutMapping
    public R<String> updateById(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //根据条件(type字段)查询分类
    @GetMapping("/list")
    public R<List<Category>> selectByType(Integer type) {
        LambdaQueryWrapper<Category> queryWrap = new LambdaQueryWrapper<>();
        //根据类型进行查询
        queryWrap.eq(type!=null,Category::getType, type);
        queryWrap.orderByAsc(Category::getSort);
        //根据顺序进行升序
        queryWrap.orderByAsc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrap);
        return R.success(list);
    }
}
